#!/usr/bin/env python
# encoding: utf-8


"""
@time: 2016/10/24 上午9:45
"""
from sympy import sympify, sin, cos, tan, cot, pi, solveset, S
from mathsolver.functions.sanjiao import sanjiao_utils as su


# 三角函数的图像和性质

def trig_cycle(trig_f, x_symbol='x'):
    """
    求三角函数的周期.y = A*sin(w*x + b)和 y = A*cos(w*x + b)最小正周期 2*pi/|w|.
    y = A*tan(w*x + b) 和 y = A*cot(w*x + b)的最小正周期是 pi/|w|
    :param trig_f: 三角函数
    :param x_symbol: x符号变量
    :return:
    >>> trig_cycle('sqrt(3)*cot(-5*x + b) + 3')
    pi/5
    >>> trig_cycle('3*sin(-5*x + b) + 3')
    2*pi/5
    """
    f = sympify(trig_f)
    d = su.trig_coefficients_dict(f)
    if len(d.items()) > 2:
        return None
    for m, c in d.items():
        if type(m) in (sin, cos):
            t = m.args[0]
            return 2 * pi / abs(t.coeff(x_symbol))
        elif type(m) in (tan, cot):
            t = m.args[0]
            return pi / abs(t.coeff(x_symbol))
    return None


F = sympify('A**2 + C**2 - 1')


# 令 T = tan(x); A = sin(x); C = cos(x)
# 则 T = A/C; A**2 + C**2 = 1
# 由一个求出另外两个
def trig_der(k, v):
    """
    :param k: T, A, B其中一个
    :param v: k对应的值
    :return:
    """
    v = sympify(v)
    d = {k: v}
    if k == 'A':  # sin(x)
        cs = list(solveset(F.subs('A', v), domain=S.Reals))
        d['C'] = cs
        ts = list(map(lambda b: v / b, cs))
        d['T'] = ts
    elif k == 'C':  # cos(x)
        f = F.subs((('A', v * sympify('T')), ('C', v)))
        ts = list(solveset(f, domain=S.Reals))
        d['T'] = ts
        a_s = list(map(lambda t: t * v, ts))
        d['A'] = a_s
    else:  # tan(x)
        cs = list(solveset(F.subs('A', v * sympify('C')), domain=S.Reals))
        d['C'] = cs
        a_s = list(map(lambda b: b * v, cs))
        d['A'] = a_s
    return d
